<template>
  <view>
    <view @tap="openPopup">
      <up-input :placeholder="placeholder" v-model="deptName" border="surround" readonly :customStyle="{
        width: '83vw',
        pointerEvents: 'none'
      }"></up-input>
    </view>

    <!-- 选择用户 -->
    <up-popup mode="right" :customStyle="{ width: '100vw', overflowY: 'auto', height: 'auto' }" v-model:show="show">
      <up-navbar title="部门选择" :autoBack="false" placeholder @leftClick="closePopup"></up-navbar>
      <OrgPicker ref="mallList" :overlay="false" :type="'dept'" :multiple="false" :entry="'component'" @ok="selected">
      </OrgPicker>
    </up-popup>
  </view>
</template>

<script>
import OrgPicker from "@/components/OrgPicker/index.vue"
import componentMinxins from '../ComponentMinxins'

export default {
  name: "DeptPicker",
  mixins: [componentMinxins],
  components: { OrgPicker },
  props: {
    value: {
      type: Array,
      default: () => {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请选择部门'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: null
    },
    label: {
      type: String,
      default: null
    },
    titleItems: {
      type: String,
      default: null
    },
    TableListValue: {
      type: Array,
      default: () => {
        return []
      }
    },
    source: {
      type: Number,
      default: 1
    },
    sourceType: {
      type: Number,
      default: 1
    },
    format: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    field: {
      type: [String, Number],
      required: true
    },
    itemId: {
      type: String,
      required: true
    },
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  watch: {
    deptName: {
      handler (newValue) {
        let value = uni.getStorageSync('formData');
        var formItems = JSON.parse(value.formItems);
        formItems.forEach(item => {
          const targetList = item?.props?.columns || item?.props?.items;
          if (item.title == this.title) {
            item.value.push(...this.selectedDept);
            uni.setStorageSync(item.id, this.selectedDept);
          } else if (this.titleItems == item.title && item.title == this.titleItems) {
            targetList.forEach(columnsitem => {
              if (columnsitem.title == this.label) {
                columnsitem.value = this.selectedDept;
                uni.setStorageSync(columnsitem.id, this.selectedDept);
              }
            })
          }
        })
      }
    }
  },
  data () {
    return {
      show: false,
      deptName: '',
      _value: '',
      fuzhiItemid: '',
      fuzhititle: '',
      selectedDept: [] // 保存选中的部门数据
    }
  },
  created () {
    this.deptName = this?.TableListValue[0]?.name || '';
    let value = uni.getStorageSync('formData');
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
      }
    })

    uni.$on('applyDeptPicker', (data) => {
      if (data?.fuzhiItemid === this.itemId) {
        this.deptName = data.data[0].name;
        this.selectedDept = data.data
        this.$emit('selectedTableList');
      }
    })
    this.setechodata()
  },
  methods: {
    setechodata () {
      // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData && this.itemId) {
        // 检查 formData 中是否存在当前 itemId 对应的字段 
        if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId)) {
          // 获取对应的值
          const fieldValue = this.ApplyDetailList.formData[this.itemId];

          // 如果值是数组，取第一个元素（根据你的数据结构）
          if (Array.isArray(fieldValue) && fieldValue.length > 0) {
            this.deptName = fieldValue[0].name
            this.selectedDept = fieldValue;
          } else {
            // 直接赋值 
            this.deptName = fieldValue
            this.selectedDept = fieldValue;
          }
        }
      }
    },
    openPopup () {
      this.fuzhiItemid = this.itemId
      this.fuzhititle = this.title
      uni.navigateTo({
        url: `/components/OrgPicker/index?overlay=false&entry=component&VisibleandHidden=true&title=部门选择&type=dept&multiple=false&source=DeptPicker&fuzhiItemid=${this.itemId}`
      });
      // this.show = true;
    },
    delDept (i) {
      this._value.splice(i, 1)
    },
    closePopup () {
      this.show = false;
      this.$refs.mallList.selection = [];
    },
    selected (dept) {
      console.log('dept', dept);
      this.show = false;
      this._value = dept.data;
      this.deptName = dept.data[0].name;
      this.selectedDept = dept.data
    },
  }
}
</script>

<style></style>
